package com.jin.udp;

import com.jin.udp.bean.Client;
import com.jin.udp.bean.IbeaconDetail;
import com.jin.udp.utils.GsonUtil;
import com.jin.udp.utils.UDPUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

/**
 * @ClassName: ForwardThread
 * @Description:
 * @Author: 12071
 * @Date: 2021/7/6 19:47
 */
public class ForwardThread extends Thread {
    /**
     * 是否继续监听 , 循环控制变量
     */
    boolean isReceive = true;

    /**
     * 存储发送数据的客户端信息
     */
    ArrayList<Client> clients = new ArrayList<>();

    @Override
    public void run() {
        super.run();

        try {
            //I. 创建 DatagramSocket 对象 , 用于 UDP 数据包的发送和接收

            //1. UDP 数据包接收者 , 监听 9000 端口
            //      该 DatagramSocket 既可以接收数据包 , 也可以发送数据包
            DatagramSocket datagramSocket = new DatagramSocket(9000);

            //II. 接收 UDP 数据包 , 无限循环接收来自客户端的信息 , 并根据不同的信息进行不同处理


            while (isReceive) {

                //2. 接收数据包使用的缓冲区
                byte[] receiveBuffer = new byte[1024];
                //3. 接收 UDP 数据包使用的 DatagramPacket 对象
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);

                //4. 接收 UDP 数据包
                datagramSocket.receive(receivePacket);

                //5. 获取发送端的 IP 地址
                String sendIP = receivePacket.getAddress().getHostAddress();
                //6. 获取发送端的端口号
                int sendPort = receivePacket.getPort();
                //7. 获取接收到的数据的长度
                int receiveLen = receivePacket.getLength();
                //8. 获取接收到的数据 , 并转为字符串
                byte[] data = Arrays.copyOfRange(receivePacket.getData(), 0, receiveLen);
                String receiveData = UDPUtils.bytesToHexString(data);
                //  String receiveData = new String(receivePacket.getData(), 0, receiveLen);
                // 截取网关Mac和终端Mac:
                String stationMac = receiveData.substring(22, 34);
                String nodeMac = receiveData.substring(38, 50);
                Integer rssi = Integer.parseInt(receiveData.substring(50, 52), 16) - 255;
                Timestamp receiveTime = new Timestamp(System.currentTimeMillis());
                if (UDPForwarder.stationMacs.stream().anyMatch(stationMac::equalsIgnoreCase) && UDPForwarder.nodes.stream().anyMatch(nodeMac::equalsIgnoreCase)) {
                    //9. 信息封装，打印接收到的数据包信息
                    IbeaconDetail ibeaconDetail = new IbeaconDetail(nodeMac, stationMac, rssi, receiveTime);
                    System.out.println("服务器 接收到 " + sendIP + " : " + sendPort + " 发送的数据:  " + ibeaconDetail.toString());

                    String payload = GsonUtil.bean2Json(ibeaconDetail);
                    byte[] buf = payload.getBytes();
                    String address = "106.52.35.169";
                    int addressPort = 8989;
                    DatagramPacket dp =
                            new DatagramPacket(buf, buf.length, InetAddress.getByName(address), addressPort);//发送至指定IP，指定端口
                    datagramSocket.send(dp);//通过send方法将数据包发送出去
                    System.out.println("转发给 " + address + ":" + addressPort);

                }
                //退出服务器循环
                if ("exit".equals(receiveData)) {
                    isReceive = false;
                }

            }


        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("服务器 运行结束");
        }
    }
}

